package LeetCode;

import java.util.PriorityQueue;

public class LeetCodeMain7 {
    public ListNode mergeKLists(ListNode[] lists) {
        if (lists==null){
            return null;
        }
        if (lists.length==1&&lists[0]==null){
            return null;
        }
        ListNode node=new ListNode(-1);
        ListNode listNode=node;
        PriorityQueue<ListNode> queue=new PriorityQueue<>(((o1, o2) -> o1.val-o2.val));
        for (int i = 0; i < lists.length; i++) {
            ListNode n2=lists[i];
            if (n2!=null){
                queue.offer(n2);
            }
        }
        while (!queue.isEmpty()){
            ListNode n1= queue.poll();
            listNode.next=n1;
            listNode=listNode.next;
            if (n1.next!=null){
                n1=n1.next;
                queue.offer(n1);
            }
        }
        listNode.next=null;
        return node.next;
    }
}
